import re
from datetime import datetime
from elasticsearch import Elasticsearch
from typing import Dict, List, Tuple, Any

from django.conf import settings

ES_HOST = settings.ES_HOST

es = Elasticsearch([ES_HOST])


class LawDocument:
    def __init__(self, id, law_name: str, volume: str, subvolume: str, chapter: str,
                 section: str, article_number: str, article_text: str):
        self.id = id
        self.law_name = law_name
        self.volume = volume
        self.subvolume = subvolume
        self.chapter = chapter
        self.section = section
        self.article_number = article_number
        self.article_text = article_text

    def serialize(self) -> Dict:
        """
        序列化法律文档数据，以便上传到 Elasticsearch。
        """
        return {
            "law_name": self.law_name,
            "volume": self.volume,
            "subvolume": self.subvolume,
            "chapter": self.chapter,
            "section": self.section,
            "article_number": self.article_number,
            "article_text": self.article_text
        }


def search_law(params) -> Tuple[List[LawDocument], int]:
    response = es.search(index="laws_index", body=params)
    # response = es.search(index="laws_test", body=params)
    hits = response['hits']['hits']
    total = response['hits']['total']['value']  # 获取总文档数

    results: list[LawDocument] = []
    for hit in hits:
        source = hit['_source']

        # print(source)

        id = hit['_id']  # 提取文档ID
        law = LawDocument(
            id=id,
            law_name=source.get('law_name', ''),
            volume=source.get('volume', ''),
            subvolume=source.get('subvolume', ''),
            chapter=source.get('chapter', ''),
            section=source.get('section', ''),
            article_number=source.get('article_number', ''),
            article_text=source.get('article_text', '')
        )
        results.append(law)
    return results, total
